package com.bootdo.app.controller;

import com.bootdo.app.htmlVO.car.Car;
import com.bootdo.app.htmlVO.car.CarGoods;
import com.bootdo.app.htmlVO.car.CarInfo;
import com.bootdo.app.utils.AppUtilXML;
import com.bootdo.app.utils.returnresponse.ServerResponse;
import com.bootdo.appsystem.domain.CarDO;
import com.bootdo.appsystem.domain.ProducesinfoDO;
import com.bootdo.appsystem.domain.SellerDO;
import com.bootdo.appsystem.domain.UseraccountDO;
import com.bootdo.appsystem.service.CarService;
import com.bootdo.appsystem.service.ProducesinfoService;
import com.bootdo.appsystem.service.SellerService;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 购物车相关
 */
@Controller
@RequestMapping("/app/car/")
public class AppCarController extends BaseController {

    @Autowired
    private CarService carService;
    @Autowired
    private ProducesinfoService producesinfoService;
    @Autowired
    private SellerService sellerService;

    //    购买商品页面
    @GetMapping("tocar")
    public String tocar(){
        return "app/goods/car";
    }

    //    购买商品页面
    @PostMapping("getCarMsg")
    @ResponseBody
    public ServerResponse getCarMsg(){
        try {
            //判断是否登录
            UseraccountDO useraccountDO = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
            if(useraccountDO == null) {
                return ServerResponse.createByErrorCodeMessage(50,"请先登录");
            }
            //获取购物车数据
            CarDO byUid = carService.getByUid(useraccountDO.getUid());
            return ServerResponse.createBySuccess(byUid);
        }catch (RuntimeException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(-1,"未知错误");
        }
    }

    //     添加购物车
    @GetMapping("addCar")
    @ResponseBody
    public ServerResponse addCar(Integer pid){
        //判断是否登录
        UseraccountDO useraccountDO = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        if(useraccountDO == null) {
            return ServerResponse.createByErrorCodeMessage(50,"请先登录");
        }

        //判断购物车是否为空,是则创建新的购物车记录
        CarDO byUid = carService.getByUid(useraccountDO.getUid());
        if (byUid == null) {
            byUid = new CarDO();
            byUid.setEdittime(new Date());
            byUid.setUid(useraccountDO.getUid());
            byUid.setCarjson(null);
            carService.save(byUid);
        }

        //获取购物车数据，转换成对象
        Car car = new Car();
        car = (Car)JSONUtils.jsonToBean(byUid.getCarjson(),car);

        //查看商品信息
        ProducesinfoDO producesinfoDO = producesinfoService.get(pid);
        //查看商家信息
        SellerDO sellerDO = sellerService.get(producesinfoDO.getSellerid());

        //判断购物车是否为null
        if (car == null) {
            //为空
            car = new Car();
            CarInfo carSeller = getCarSeller(sellerDO);
            ArrayList<CarInfo> carInfos = new ArrayList<>();
            CarGoods carGoods = getCarGoods(producesinfoDO);
            List<CarGoods> goodList = new ArrayList<CarGoods>();
            goodList.add(carGoods);
            carSeller.setGoodList(goodList);
            carInfos.add(carSeller);
            car.setCarInfo(carInfos);
        }else {
            //判断购物车是否有商家信息
            if(car.getCarInfo() == null){
                //没有信息
                CarInfo carSeller = getCarSeller(sellerDO);
                ArrayList<CarInfo> carInfos = new ArrayList<>();
                CarGoods carGoods = getCarGoods(producesinfoDO);
                List<CarGoods> goodList = new ArrayList<CarGoods>();
                goodList.add(carGoods);
                carSeller.setGoodList(goodList);
                carInfos.add(carSeller);
                car.setCarInfo(carInfos);
            }else {
                //循环数据，获取购物车中商家商品数据
                for (CarInfo carInfo : car.getCarInfo()){
                    //判断商品是否是已存在商家
                    if (carInfo.getSellerId() == sellerDO.getSellerid()) {
                        //已存在商家信息，给购物车商家下添加商品
                        System.out.println("【goods】" + carInfo);
                        for (CarGoods carGoods : carInfo.getGoodList()){
                            if(carGoods.getPid() == pid){
                                //购物车中已存在数据
                                return ServerResponse.createBySuccess("购物车中已存在该商品");
                            }
                        }
                        //不存在该商品
                        CarGoods carGoods = getCarGoods(producesinfoDO);
                        List<CarGoods> goodList = carInfo.getGoodList();
                        if(goodList == null || goodList.size() < 1){
                            goodList = new ArrayList<CarGoods>();
                            goodList.add(carGoods);
                            carInfo.setGoodList(goodList);
                        }else {
                            carInfo.getGoodList().add(carGoods);
                        }
                        //始终保存一下购物车信息
                        String s = JSONUtils.beanToJson(car);
                        byUid.setEdittime(new Date());
                        byUid.setCarjson(s);
                        carService.update(byUid);
                        return ServerResponse.createBySuccess("添加成功");
                    }
                }
                //不存在该商家
                CarInfo carSeller = getCarSeller(sellerDO);
                CarGoods carGoods = getCarGoods(producesinfoDO);
                List<CarGoods> goodList = new ArrayList<CarGoods>();
                goodList.add(carGoods);
                carSeller.setGoodList(goodList);
                List<CarInfo> carInfos = car.getCarInfo();
                carInfos.add(carSeller);
                car.setCarInfo(carInfos);
            }
        }

        //始终保存一下购物车信息
        String s = JSONUtils.beanToJson(car);
        byUid.setEdittime(new Date());
        byUid.setCarjson(s);
        carService.update(byUid);
        return ServerResponse.createBySuccess("添加成功");
    }

    /**
     * 存放购物车中商家信息
     * @param sellerDO 查询到的商家信息
     * @return
     */
    private CarInfo getCarSeller(SellerDO sellerDO){
        CarInfo carInfo = new CarInfo();
        carInfo.setSellerId(sellerDO.getSellerid());
        carInfo.setSellerImage(sellerDO.getSellerimage());
        carInfo.setSellerName(sellerDO.getSellername());
        carInfo.setChecked(0);
        return carInfo;
    }

    /**
     * 存放购物车中商品信息
     * @param producesinfoDO 查询的商品信息
     * @return
     */
    private CarGoods getCarGoods(ProducesinfoDO producesinfoDO){
        CarGoods carGoods = new CarGoods();
        carGoods.setPid(producesinfoDO.getPid());
        carGoods.setGoodsTitle(producesinfoDO.getPname());
        carGoods.setVolume(producesinfoDO.getVolume());
        carGoods.setPrice(producesinfoDO.getShopprice());
        carGoods.setIsChick(0);
        carGoods.setImgUrl(producesinfoDO.getFavorable());
        carGoods.setNumber(1);
        return carGoods;
    }




    //     修改购物车
    @PostMapping("editCar")
    @ResponseBody
    public ServerResponse editCar(String cardata){
        try {
            //判断是否登录
            UseraccountDO useraccountDO = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
            if(useraccountDO == null) {
                return ServerResponse.createByErrorCodeMessage(50,"请先登录");
            }

            //判断购物车是否为空,是则创建新的购物车记录
            CarDO byUid = carService.getByUid(useraccountDO.getUid());
            if (byUid == null) {
                byUid = new CarDO();
                byUid.setUid(useraccountDO.getUid());
                byUid.setCarjson(null);
                byUid.setEdittime(new Date());
                carService.save(byUid);
            }
            //更新购物车信息
            byUid.setCarjson(cardata);
            carService.update(byUid);
            return ServerResponse.createBySuccess();
        }catch (RuntimeException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(-1,"未知错误");
        }
    }

//    public static void main(String[] args) {
//        Car car = new Car();
//        car = (Car)JSONUtils.jsonToBean("{\"carInfo\":[{\"checked\":0,\"goodList\":[{\"goodsTitle\":\"菊茶500g\",\"imgUrl\":\"/files/seller/uid1/20180716/2018071641eca903-c1b1-43ad-b011-dc1b3e26b1d7.jpg\",\"isChick\":0,\"number\":2,\"pid\":14,\"price\":998,\"volume\":20}],\"sellerId\":1,\"sellerImage\":\"/files/seller/uid1/20180712/20180712c8e9629e-0084-455c-af47-e0a3b1081916.jpg\",\"sellerName\":\"禹州酒业有限公司\"}]}", car);
//        System.out.println(car);
//    }


}
